from django.core.management.base import BaseCommand
from apps.tasks.models import Tasks
from datetime import datetime, timedelta
import random


class Command(BaseCommand):
    help = '往tasks表插入100条测试数据'

    def handle(self, *args, **options):
        # 定义一些可能的数据值
        epic_names = ['项目规划', '系统开发', '测试阶段', '上线部署', '维护阶段']
        story_names = ['用户管理功能', '数据统计模块', '报表生成功能', '系统配置', '权限管理']
        task_types = ['开发', '测试', '设计', '文档', '部署']
        projects = ['WMS系统', 'CRM系统', 'ERP系统', 'OA系统', 'BI系统']
        versions = ['v1.0', 'v1.1', 'v1.2', 'v2.0', 'v2.1']
        product_managers = ['张三', '李四', '王五', '赵六', '钱七']
        statuses = ['待开始', '进行中', '已完成', '已暂停', '已取消']
        responsible_persons = ['开发者A', '开发者B', '开发者C', '开发者D', '开发者E']

        # 开始插入数据
        self.stdout.write('开始插入数据...')
        tasks_to_create = []
        
        # 生成当前日期
        today = datetime.now().date()
        
        for i in range(100):
            # 生成唯一的task_id
            task_id = f'TASK{i:03d}'
            
            # 随机生成计划开始和结束日期
            start_days = random.randint(0, 30)
            end_days = random.randint(start_days + 1, start_days + 15)
            plan_start_time = today + timedelta(days=start_days)
            plan_end_time = today + timedelta(days=end_days)
            
            # 随机生成实际开始和结束日期（字符串格式）
            actual_start_time = plan_start_time.strftime('%Y-%m-%d') if random.choice([True, False]) else None
            actual_end_time = plan_end_time.strftime('%Y-%m-%d') if actual_start_time and random.choice([True, False]) else None
            
            # 创建任务对象
            task = Tasks(
                epic_name=random.choice(epic_names),
                story_name=random.choice(story_names),
                task_id=task_id,
                task_name=f'任务{i+1}: {random.choice(story_names)} - {random.choice(task_types)}',
                task_type=random.choice(task_types),
                project=random.choice(projects),
                fc_publish_version=random.choice(versions),
                product_manager=random.choice(product_managers),
                status=random.choice(statuses),
                fc_responsible_person=random.choice(responsible_persons),
                estimate_time=round(random.uniform(1.0, 10.0), 2),
                fc_plan_start_time=plan_start_time,
                fc_plan_end_time=plan_end_time,
                fc_actual_start_time=actual_start_time,
                fc_actual_end_time=actual_end_time
            )
            tasks_to_create.append(task)
        
        # 批量创建数据
        Tasks.objects.bulk_create(tasks_to_create)
        
        self.stdout.write(self.style.SUCCESS('成功插入100条数据到tasks表！'))